<template>
  <div class="h-100" style="display: flex; flex-direction: column">
    <NavBar
      bg-white
      no-gap
      ref="navbarRef"
      :data="taskNavBar"
      :activeIndex="navbarActiveIndex"
      @click-navbar="clickNavBar"
    />
    <div class="publish-btn">
      <a-button type="primary" @click="publishTask">{{
        $t("btnText.publish_task")
      }}</a-button>
    </div>
    <!-- pc 表格 -->
    <div class="flex-1 pc-table">
      <Table
        font-family="MiSans, MiSans"
        size="small"
        striped
        theadBgColor="#e6edf2"
        :data="tableData"
        :columns="taskColumns"
      >
        <template #status="{ row }">
          <div class="status success" v-if="row.status == 3 || row.status == 4">
            {{ row.status_title }}
          </div>
          <div class="status danger" v-if="row.status == 1 || row.status == 2">
            {{ row.status_title }}
          </div>
        </template>
        <template #operate="{ row }">
          <div class="operate">
            <div class="btn" @click="getTaskDetailData(row.id)">
              <IconDetail />
              <span>{{ $t("btnText.detail") }}</span>
            </div>
            <template v-if="row.status == 3">
              <span>|</span>
              <div class="btn" @click="followUpBtn(row._rawData)">
                <IconFollowUp />
                <span v-if="row._rawData.receive_id == profile?.id">{{
                  $t("btnText.follow_up")
                }}</span>
                <span v-else>{{ $t("btnText.replay") }}</span>
              </div>
            </template>
          </div>
        </template>
      </Table>
    </div>
    <!-- 移动端布局 -->
    <TaskMobile
      @getTaskDetailData="getTaskDetailData"
      @publishTask="publishTask"
      @followUp="followUpBtn"
      :data="tableData"
      showAdd
    />
    <div class="show_more_container">
      <ShowMore
        pagerMb="0"
        v-model:currentPage="listParams.page"
        :totalCount="listParams.total"
        @change="getTableData"
      />
    </div>
  </div>
  <!-- 弹窗 -->
  <!-- 任务详情 -->
  <DialogTaskDetail ref="dialogTaskDetailRef" :id="task_id" />
  <!-- 任务填写表单 -->
  <DialogTaskFill
    ref="dialogTaskFillRef"
    :type="dialogTaskFillType"
    :id="task_id"
    :task_title="task_title"
    @complete="getTableData"
  />
  <!-- 任务跟进记录 -->
  <DialogTaskFollowUp
    ref="dialogTaskFollowUp"
    :id="task_id"
    :task_title="task_title"
    @apply-statement="getTableData"
  />
  <!-- 更新个人姓名 -->
  <FormModalMemberUpdateNickname ref="formModalMemberUpdateNickname" />
</template>

<script setup lang="ts">
import { message } from "ant-design-vue";
import {
  defineAsyncComponent,
  watch,
  ref,
  nextTick,
  getCurrentInstance,
  onMounted,
} from "vue";
import { postMemberTaskList, postTaskFollowUpList } from "../../../../api/task";
import { useMemberStore } from "../../../../store";
import type { TaskItem } from "../../../../types/task";
import { taskNavBar } from "../a_data/navbar";
import { taskColumns } from "../a_data/table";
const NavBar = defineAsyncComponent(() => import("../a_components/navbar"));
const Table = defineAsyncComponent(() => import("../a_components/table"));
const TaskMobile = defineAsyncComponent(() => import("./taskMobile.vue"));
const $t = getCurrentInstance()?.appContext.config.globalProperties.$t;
const { profile } = useMemberStore();
const memberStore = useMemberStore();

// 点击 navbar
const navbarActiveIndex = ref(0);
const clickNavBar = ({ item, index }) => {
  navbarActiveIndex.value = index;
  listParams.value.page = 1;
  getTableData();
};
const navbarRef = ref();
watch(
  () => memberStore.AppLang,
  () => {
    navbarRef.value.refresh();
  }
);
let task_navbar_index = sessionStorage.getItem("task_navbar_index");
if (task_navbar_index) {
  navbarActiveIndex.value = parseInt(task_navbar_index);
}

// 发布任务
const dialogTaskFillType = ref("publish");
const dialogTaskFillRef = ref();
const dialogTaskFollowUp = ref();
const task_id = ref();
const task_title = ref("");
const formModalMemberUpdateNickname = ref();
const publishTask = () => {
  let last_name = profile?.last_name;
  let first_name = profile?.first_name;
  if (!last_name || !first_name) {
    message.warning($t("message.perfect_information"));
    if (isMobile()) goto("/mobile/updateName");
    else formModalMemberUpdateNickname.value.show();
    return;
  }
  if (isMobile()) {
    goto("/mobile/publishTask");
  } else {
    dialogTaskFillType.value = "publish";
    task_title.value = "";
    nextTick(() => {
      dialogTaskFillRef.value.showDialog();
    });
  }
};

// 表格数据
const tableData = ref();
const listParams = ref({
  page: 1,
  total: 0,
});
const getTableData = async () => {
  let status = taskNavBar[navbarActiveIndex.value].id;
  let { page } = listParams.value;
  let res = await postMemberTaskList({ status, page });
  if (res.code === 200) {
    tableData.value = res.data.data.map((item) => {
      return {
        id: item.id,
        task_no: item.task_no,
        publisher: item.member_last_name +' '+ item.member_first_name,
        receiver: item.receive_last_name +' '+ item.receive_first_name,
        time: item.create_time.split(" ")[0],
        title: item.title,
        status: item.status,
        status_title: item.status_title,
        _rawData: item,
      };
    });
    listParams.value.total = res.data.total;
  }
};
getTableData();

// =============任务详情 =================
const dialogTaskDetailRef = ref();
const getTaskDetailData = async (id: number) => {
  if (isMobile()) {
    goto("/mobile_detail/task", { id });
    return;
  }
  task_id.value = id;
  nextTick(() => {
    dialogTaskDetailRef.value.showDialog();
  });
};

// =============任务跟进=================
const followData = ref();
const followUpBtn = async (item: TaskItem, type: string) => {
  if (item.status == 1)
    return message.warning($t("message.task_follow_error.pre_audit"));
  if (item.status == 2)
    return message.warning($t("message.task_follow_error.published"));
  dialogTaskFillType.value = type;
  task_title.value = item.title;
  let id = item.id;
  // 任务跟进记录-弹窗
  if (task_id.value == id && followData.value?.length > 0) {
    if (isMobile()) {
      sessionStorage.setItem("taskDetailData", JSON.stringify(item));
      sessionStorage.setItem("task_navbar_index", navbarActiveIndex.value + "");
      goto("/mobile/followUp", { task_id: item.id });
      return;
    }
    dialogTaskFollowUp.value.showDialog();
    return;
  }
  task_id.value = id;
  let res = await postTaskFollowUpList(id);
  followData.value = res.data;
  // 记录为0 弹窗第一次跟进弹窗 否则直接弹窗更近记录弹窗
  if (res.data.length == 0) {
    // 发布者-没数据提示等待接单者跟进记录
    if (
      item.status == 3 &&
      (profile?.id == item.member_id || profile?.id == item?._rawData?.id)
    )
      return message.warning($t("message.task_follow_error.received"));
    if (isMobile()) {
      sessionStorage.setItem("task_navbar_index", navbarActiveIndex.value + "");
      goto("/mobile/publishTask", { type: dialogTaskFillType.value });
      return;
    }
    dialogTaskFillType.value = 'follow'
    // 接单者-弹窗跟进
    nextTick(() => {
      dialogTaskFillRef.value.showDialog();
    });
    return;
  }
  // 跟进记录弹窗
  if (isMobile()) {
    sessionStorage.setItem("task_navbar_index", navbarActiveIndex.value + "");
    goto("/mobile/followUp", { task_id: item.id });
    return;
  }
  nextTick(() => {
    dialogTaskFollowUp.value.showDialog();
  });
};
</script>
<style scoped lang="less">
.publish-btn {
  margin: 24px 0;
  .ant-btn {
    height: 40px !important;
    border-radius: 12px !important;
    font-size: 14px !important;
  }
}
.operate {
  display: flex;
  align-items: center;
  .btn {
    display: flex;
    align-items: center;
    white-space: nowrap;
    gap: 4px;
    padding: 0;
    font-size: 16px;
  }
  & > span {
    color: #ccd6de;
    margin: 0 10px;
  }
}
.add-new-task {
  position: fixed;
  bottom: 300px;
  right: 200px;
  z-index: 9;
  border-radius: 50%;
  display: none;
  .svg-icon {
    width: 200px;
    height: 200px;
  }
}
@media screen and (max-width: 768px) {
  .publish-btn {
    display: none;
  }
  .add-new-task {
    display: block;
  }
  .pc-table {
    display: none;
  }
  .show_more_container {
    background-color: #f6f8fa;
    margin-left: -82px;
    margin-right: -82px;
  }
}
</style>
